import hashlib
import os
# import


def md5_file(file:str):
    m = hashlib.md5()
    with open(file,'rb') as f:
        m.update(f.read())
    return m.hexdigest()
    # raise Exception("md5_file未完成!")


def md5_folder(folder):
    all = os.listdir(folder)
    all_abs = [os.path.abspath(os.path.join(folder,file)) for file in all]
    files = [file for file in all_abs if os.path.isfile(file)]
    files.sort()
    # print(files)
    m = hashlib.md5()
    for file in files:
        m.update(md5_file(file).encode('utf-8'))
    return m.hexdigest()


def report_folder(Folder,c=False):
    if not os.path.exists(Folder) and c:
        os.mkdir(Folder)
    assert os.path.isdir(Folder)
    all = [os.path.abspath(os.path.join(Folder, file)) for file in os.listdir(Folder)]
    files = [file for file in all if os.path.isfile(file)]
    folders = [folder for folder in all if os.path.isdir(folder)]
    files.sort()
    # print(files)
    md5s = {}
    m = hashlib.md5()
    for file in files:
        md5s[file] = md5_file(file)
        assert type(md5s[file])==str and len(md5s[file])==32
        m.update(md5s[file].encode("utf-8"))
    return {
        "path":Folder,
        "md5":m.hexdigest(),
        "files":md5s,
        "folders":folders,
    }


def file_out(file):
    with open(file, 'rb') as f:
        return f.read()


def file_in(file,data):
    with open(file,'wb') as f:
        f.write(data)


def deletes(files):
    for file in files:
        os.remove(file)

def delete_folder(folder):
    assert os.path.isdir(folder)
    os.system("rm -rf {}".format(folder))


